package com.yunhe.authority.repository.authority.impl;

import com.yunhe.authority.domain.authority.ResourceTree;
import org.neo4j.ogm.model.Result;
import org.neo4j.ogm.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资源树数据仓库自定义实现
 * @desc 资源树数据仓库自定义实现
 * @author liuronglei
 */
@Repository
public class ResourceTreeDao {
    @Autowired
    Session session;

    /**
     * 根据单位获得单位关联的资源树列表
     * @param firmId 单位ID
     */
    public List<ResourceTree> findResourceTree(Long firmId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("firmId", firmId);
        List<ResourceTree> list = new ArrayList<>();
        String cypher = "match(f:Firm)-[r:HAS_RESOURCE]->(res) where ID(f)={firmId} return"
                + " ID(res) as id,r.type as type,not exists((res)-[:HAS_CHILD]->()) as leaf";
        Result result = session.query(cypher, paramMap);
        for (Map<String, Object> object : result) {
            ResourceTree resourceTree = new ResourceTree();
            resourceTree.setId(((Integer)object.get("id")).longValue());
            resourceTree.setType((String)object.get("type"));
            resourceTree.setLeaf((Boolean)object.get("leaf"));
            list.add(resourceTree);
        }
        return list;
    }
}
